package controllers {
	import away3d.cameras.Camera3D;
	import away3d.containers.ObjectContainer3D;
	import away3d.controllers.HoverController;
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.media.Camera;
	/**
	 * 盘旋控制器
	 */
	public class OrbitController {
		private var _camera:Camera3D;
		private var _stage:DisplayObject;
		private var _target:ObjectContainer3D;
		private var _controller:HoverController;
		private var _fov:Number = 800;
		
		private var _lastPanAngle:Number;
		private var _lastTiltAngle:Number;
		private var _lastMouseX:Number;
		private var _lastMouseY:Number;
		private var _isMouseDown:Boolean = false;
		private var _activate:Boolean;
		
		public function OrbitController(camera:Camera3D,stage:DisplayObject,target:ObjectContainer3D = null) {
			_camera = camera;
			_stage = stage;
			_target = target;
			_controller = new HoverController(_camera, _target, 180, 20, _fov, 0, 35, NaN, NaN, 6, 1);
		}	
		
		private function activateController(bool:Boolean):void {
			if (bool) {
				_stage.addEventListener(MouseEvent.MOUSE_DOWN, onStageMouseDown);
				_stage.addEventListener(MouseEvent.MOUSE_UP, onStageMouseUp);
				_stage.addEventListener(MouseEvent.MOUSE_WHEEL, onStageMouseWheel);
			}else {
				_stage.removeEventListener(MouseEvent.MOUSE_DOWN, onStageMouseDown);
				_stage.removeEventListener(MouseEvent.MOUSE_UP, onStageMouseUp);
				_stage.removeEventListener(MouseEvent.MOUSE_WHEEL, onStageMouseWheel);
			}
		}
		
		private function onStageMouseWheel(e:MouseEvent):void {
			var value:Number = _fov - e.delta * 2;
			_fov = value<590?590:value>950?950:value;
		}
		
		private function onStageMouseUp(e:MouseEvent):void {
			_isMouseDown = false;
		}
		
		private function onStageMouseDown(e:MouseEvent):void {
			_lastPanAngle = _controller.panAngle;
			_lastTiltAngle = _controller.tiltAngle;
			_lastMouseX = _stage.mouseX;
			_lastMouseY = _stage.mouseY;
			_isMouseDown = true;
		}
		
		public function update():void {
			if (_activate) {
				_controller.update();
				_controller.distance = _controller.distance + (_fov - _controller.distance) / 5;
				if (_isMouseDown) {
					_controller.panAngle = (_stage.mouseX - _lastMouseX) * 0.3 + _lastPanAngle;
					_controller.tiltAngle = (_stage.mouseY - _lastMouseY) * 0.3 + _lastTiltAngle;
				}
			}
		}
		
		public function get activate():Boolean {
			return _activate;
		}
		
		public function set activate(value:Boolean):void {
			_activate = value;
			activateController(value);
		}
	}
}